using System.Net.WebSockets;
using Microsoft.AspNetCore.Mvc;
using Vin.AspNetCore.Core.Controller;
using Vin.Event;
using Vin.WebApi.Tests.EventArgs;
using Vin.WebApi.Tests.Models;
using Vin.WebApi.Tests.Sse;

namespace Vin.WebApi.Tests.Controllers;

public class Test2Controller : VinBaseController
{
    // [Inject] private readonly ISseService _sseService = null!;


    [HttpGet("/test2")]
    public IActionResult Get(string data)
    {
        VinEventManager.Fire<TestSmsEventArg>(this, new TestSmsEventArg()
        {
            Data = data
        });

        return Success();
    }

    // [HttpGet("/test3")]
    // public async Task Get2()
    // {
    //     Response.ContentType = "text/event-stream";
    //     Response.Headers.Append("Cache-Control", "no-cache");
    //     Response.Headers.Append("Connection", "keep-alive");
    //
    //     await Response.WriteAsync("data: 1111241541324654124\n\n");
    //     await Response.Body.FlushAsync();
    //
    //     var i = 0;
    //     while (!HttpContext.RequestAborted.IsCancellationRequested)
    //     {
    //         i++;
    //         await Response.WriteAsync($"data: {i}\n\n");
    //         await Response.Body.FlushAsync();
    //         await Task.Delay(1000);
    //     }
    //
    //     var close = true;
    // }


    [HttpGet("/test4")]
    public async Task Get4()
    {
        if (HttpContext.WebSockets.IsWebSocketRequest)
        {
            var socket = await HttpContext.WebSockets.AcceptWebSocketAsync();
            var buffer = new byte[1024 * 4];
            var result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            while (!result.CloseStatus.HasValue)
            {
                await socket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType,
                    result.EndOfMessage, CancellationToken.None);
                result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            }

            var close = true;
        }
        else
        {
            HttpContext.Response.StatusCode = 400;
        }
    }
}